import 'package:flutter/material.dart';
import '../models/heritage_activity.dart';
import '../services/heritage_activity_service.dart';
import '../widgets/loading_widget.dart';
import '../widgets/error_widget.dart';

class ActivityDetailScreen extends StatefulWidget {
  final String activityId;

  const ActivityDetailScreen({
    Key? key,
    required this.activityId,
  }) : super(key: key);

  @override
  State<ActivityDetailScreen> createState() => _ActivityDetailScreenState();
}

class _ActivityDetailScreenState extends State<ActivityDetailScreen> {
  final HeritageActivityService _activityService = HeritageActivityService();
  HeritageActivity? _activity;
  bool _isLoading = true;
  bool _isRegistered = false;
  bool _isRegistering = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadActivityDetail();
  }

  Future<void> _loadActivityDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      final activity = await _activityService.getActivityById(widget.activityId);
      if (activity != null) {
        // 模拟用户ID
        const userId = 'user_123';
        final isRegistered = await _activityService.isUserRegistered(widget.activityId, userId);
        
        setState(() {
          _activity = activity;
          _isRegistered = isRegistered;
          _isLoading = false;
        });
      } else {
        setState(() {
          _error = '活动不存在';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _handleRegistration() async {
    if (_activity == null || _isRegistering) return;

    try {
      setState(() {
        _isRegistering = true;
      });

      const userId = 'user_123';
      
      if (_isRegistered) {
        await _activityService.cancelRegistration(widget.activityId, userId);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('取消报名成功')),
        );
      } else {
        await _activityService.registerForActivity(widget.activityId, userId);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('报名成功')),
        );
      }

      // 重新加载活动详情
      await _loadActivityDetail();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(e.toString())),
      );
    } finally {
      setState(() {
        _isRegistering = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('活动详情'),
        ),
        body: const LoadingWidget(),
      );
    }

    if (_error != null) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('活动详情'),
        ),
        body: ErrorWidgetCustom(
          error: _error!,
          onRetry: _loadActivityDetail,
        ),
      );
    }

    if (_activity == null) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('活动详情'),
        ),
        body: const Center(
          child: Text('活动不存在'),
        ),
      );
    }

    return Scaffold(
      body: CustomScrollView(
        slivers: [
          _buildSliverAppBar(),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildBasicInfo(),
                  const SizedBox(height: 24),
                  _buildDescription(),
                  const SizedBox(height: 24),
                  _buildTimeAndLocation(),
                  const SizedBox(height: 24),
                  _buildParticipantInfo(),
                  const SizedBox(height: 24),
                  _buildRequirements(),
                  const SizedBox(height: 24),
                  _buildHighlights(),
                  const SizedBox(height: 24),
                  _buildTags(),
                  const SizedBox(height: 100), // 为底部按钮留出空间
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 250,
      pinned: true,
      flexibleSpace: FlexibleSpaceBar(
        title: Text(
          _activity!.title,
          style: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            shadows: [
              Shadow(
                offset: Offset(0, 1),
                blurRadius: 3,
                color: Colors.black54,
              ),
            ],
          ),
        ),
        background: Stack(
          fit: StackFit.expand,
          children: [
            Image.network(
              _activity!.imageUrl,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  color: Colors.grey[300],
                  child: const Icon(
                    Icons.image_not_supported,
                    size: 50,
                    color: Colors.grey,
                  ),
                );
              },
            ),
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.transparent,
                    Colors.black.withOpacity(0.7),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.share),
          onPressed: () {
            // TODO: 实现分享功能
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('分享功能待实现')),
            );
          },
        ),
      ],
    );
  }

  Widget _buildBasicInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            _buildCategoryChip(),
            const SizedBox(width: 8),
            _buildStatusChip(),
          ],
        ),
        const SizedBox(height: 12),
        Text(
          _activity!.title,
          style: Theme.of(context).textTheme.headlineSmall?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Icon(
              Icons.business,
              size: 16,
              color: Colors.grey[600],
            ),
            const SizedBox(width: 4),
            Text(
              '主办方：${_activity!.organizer}',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 14,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildCategoryChip() {
    final category = _activity!.category;
    Color chipColor;
    String categoryText;
    
    switch (category) {
      case 'workshop':
        chipColor = Colors.blue;
        categoryText = '工作坊';
        break;
      case 'exhibition':
        chipColor = Colors.green;
        categoryText = '展览';
        break;
      case 'performance':
        chipColor = Colors.purple;
        categoryText = '演出';
        break;
      case 'lecture':
        chipColor = Colors.orange;
        categoryText = '讲座';
        break;
      case 'festival':
        chipColor = Colors.red;
        categoryText = '节庆';
        break;
      case 'competition':
        chipColor = Colors.teal;
        categoryText = '比赛';
        break;
      default:
        chipColor = Colors.grey;
        categoryText = '其他';
        break;
    }
    
    return Chip(
      label: Text(
        categoryText,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
      backgroundColor: chipColor,
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
    );
  }

  Widget _buildStatusChip() {
    final status = _activity!.status;
    Color chipColor;
    String statusText;
    
    switch (status) {
      case ActivityStatus.upcoming:
        chipColor = Colors.green;
        statusText = '即将开始';
        break;
      case ActivityStatus.ongoing:
        chipColor = Colors.blue;
        statusText = '进行中';
        break;
      case ActivityStatus.completed:
        chipColor = Colors.grey;
        statusText = '已结束';
        break;
      case ActivityStatus.cancelled:
        chipColor = Colors.red;
        statusText = '已取消';
        break;
      case ActivityStatus.full:
        chipColor = Colors.amber;
        statusText = '已满员';
        break;
      case ActivityStatus.suspended:
        chipColor = Colors.orange;
        statusText = '已暂停';
        break;
    }
    
    return Chip(
      label: Text(
        statusText,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
      backgroundColor: chipColor,
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
    );
  }

  Widget _buildDescription() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '活动介绍',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          _activity!.description,
          style: const TextStyle(
            fontSize: 16,
            height: 1.5,
          ),
        ),
      ],
    );
  }

  Widget _buildTimeAndLocation() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '时间地点',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        _buildInfoRow(
          Icons.access_time,
          '开始时间',
          _formatDateTime(_activity!.startDate),
        ),
        const SizedBox(height: 8),
        _buildInfoRow(
          Icons.access_time_filled,
          '结束时间',
          _formatDateTime(_activity!.endDate),
        ),
        const SizedBox(height: 8),
        _buildInfoRow(
          Icons.location_on,
          '活动地点',
          _activity!.location,
        ),
      ],
    );
  }

  Widget _buildParticipantInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '参与信息',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        _buildInfoRow(
          Icons.people,
          '参与人数',
          '${_activity!.currentParticipants}/${_activity!.maxParticipants}',
        ),
        const SizedBox(height: 8),
        _buildInfoRow(
          Icons.attach_money,
          '活动费用',
          _activity!.price > 0 ? '¥${_activity!.price.toStringAsFixed(0)}' : '免费',
        ),
      ],
    );
  }

  Widget _buildRequirements() {
    if (_activity!.requirements.isEmpty) return const SizedBox.shrink();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '参与要求',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        ...(_activity!.requirements.map((requirement) => Padding(
          padding: const EdgeInsets.only(bottom: 4),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('• ', style: TextStyle(fontSize: 16)),
              Expanded(
                child: Text(
                  requirement,
                  style: const TextStyle(fontSize: 14),
                ),
              ),
            ],
          ),
        ))),
      ],
    );
  }

  Widget _buildHighlights() {
    if (_activity!.highlights.isEmpty) return const SizedBox.shrink();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '活动亮点',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        ...(_activity!.highlights.map((highlight) => Padding(
          padding: const EdgeInsets.only(bottom: 4),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Icon(
                Icons.star,
                size: 16,
                color: Colors.amber,
              ),
              const SizedBox(width: 4),
              Expanded(
                child: Text(
                  highlight,
                  style: const TextStyle(fontSize: 14),
                ),
              ),
            ],
          ),
        ))),
      ],
    );
  }

  Widget _buildTags() {
    if (_activity!.tags.isEmpty) return const SizedBox.shrink();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '相关标签',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 4,
          children: _activity!.tags.map((tag) => Chip(
            label: Text(
              tag,
              style: const TextStyle(fontSize: 12),
            ),
            backgroundColor: Colors.grey[200],
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          )).toList(),
        ),
      ],
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(
          icon,
          size: 20,
          color: Colors.grey[600],
        ),
        const SizedBox(width: 8),
        SizedBox(
          width: 80,
          child: Text(
            label,
            style: TextStyle(
              color: Colors.grey[600],
              fontSize: 14,
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBottomBar() {
    final canRegister = _activity!.status == ActivityStatus.upcoming &&
        _activity!.currentParticipants < _activity!.maxParticipants;
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.3),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, -3),
          ),
        ],
      ),
      child: Row(
        children: [
          if (_activity!.price > 0) ...[
            Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '活动费用',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                Text(
                  '¥${_activity!.price.toStringAsFixed(0)}',
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                  ),
                ),
              ],
            ),
            const SizedBox(width: 16),
          ],
          Expanded(
            child: ElevatedButton(
              onPressed: canRegister ? _handleRegistration : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: _isRegistered ? Colors.grey : Theme.of(context).primaryColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: _isRegistering
                  ? const SizedBox(
                      height: 20,
                      width: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(
                      _getButtonText(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  String _getButtonText() {
    if (_activity!.status != ActivityStatus.upcoming) {
      return '活动已结束';
    }
    
    if (_activity!.currentParticipants >= _activity!.maxParticipants) {
      return '活动已满';
    }
    
    return _isRegistered ? '取消报名' : '立即报名';
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 '
        '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}